package com.fs.system.security;

import com.fs.common.core.pojo.SysUser;
import com.fs.common.core.vo.LoginUser;
import com.fs.common.enums.UserStatus;
import com.fs.common.exception.ServiceException;
import com.fs.common.exception.user.UserNotExistsException;
import com.fs.system.mapper.SysUserMapper;
import com.fs.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Objects;

/**
 * @author suke
 * @version 1.0
 * @title UserDetailsServiceImpl
 * @description
 * @create 2024/7/25 10:44
 */
@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private ISysUserService  sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //3,根据用户名查询用户
        SysUser sysUser = sysUserService.selectUserByName(username);
        //验证用户是否存在, 状态正常
        if (Objects.isNull(sysUser)) {
            throw new UserNotExistsException();
        }
        //是否禁用
        if (sysUser.getStatus() == UserStatus.DISABLE.getCode()) {
            throw new ServiceException("用户已封禁，请联系管理员");
        }
        //是否删除
        if (sysUser.getDelFlag() == UserStatus.DELETED.getCode()) {
            throw new ServiceException("对不起，您的账号已被删除");
        }

        return createLoginUser(sysUser);
    }

    public LoginUser createLoginUser(SysUser sysUser){
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setUser(sysUser);
        loginUser.setDeptId(sysUser.getDeptId());
        return loginUser;
    }
}
